package org.cloud.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.Data;
import org.cloud.model.TFrameMenu;
import org.cloud.model.TFrameRole;
import org.cloud.vo.UserRole;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

@Data
@JsonInclude(Include.NON_EMPTY)
public class LoginUserDetails implements UserDetails {

   private Long id;
   private String username;
   private String password;
   @JsonIgnore
   private Collection<TFrameRole> roles = new ArrayList<>();
   private Set<UserRole> userRoles = new HashSet<>();
   @JsonIgnore
   private Collection<TFrameMenu> frameMenuList = new ArrayList<>();
   private Collection<GrantedAuthority> authorities;
   private String token;
   public String userType;
   private String defaultRole;
   private String userRegistSource;
   private String sessionKey;
   private String sex;
   private String email;
   private String fullName;
   private String mobilePhone;
   private Integer status;
   private String avatar;
   private Map<String, Set<String>> userDataDimensionMap;
   private List<String> apiEncryptKey;

   public Collection<TFrameRole> getRoles() {
      if (roles == null) {
         roles = new ArrayList<>();
      }
      return roles;
   }

   @Override
   @JsonIgnore
   public Collection<GrantedAuthority> getAuthorities() {
      if (authorities != null) {
         return authorities;
      }
      List<String> roleList = new ArrayList<>();
      for (TFrameRole frameRole : getRoles()) {
         roleList.add(frameRole.getRoleCode());
      }
      authorities = AuthorityUtils.createAuthorityList(roleList.toArray(new String[]{}));
      return authorities;
   }

   @Override
   public boolean isAccountNonExpired() {
      return status != -1;
   }

   @Override
   public boolean isAccountNonLocked() {
      return status != -2;
   }

   @Override
   public boolean isCredentialsNonExpired() {
      return true;
   }

   @Override
   public boolean isEnabled() {
      return status > 0;
   }

   public Collection<TFrameMenu> getFrameMenuList() {
      if (frameMenuList == null) {
         frameMenuList = new ArrayList<>();
      }
      return frameMenuList;
   }

   public void setFrameMenuList(Collection<TFrameMenu> frameMenuList) {
      this.frameMenuList = frameMenuList;
   }

   private static final long serialVersionUID = -6997588753870506318L;
}
